package com.study.springcache.controller;

import com.study.springcache.controller.vo.UserVo;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TestController {

    // 将数据加入到缓存中，value:缓存区域，key:缓存的key，key可以使用spel表达式来获取方法信息
    @Cacheable(value = {"testData"}, key = "'myData'", sync = true)
    @GetMapping("/test")
    public List<UserVo> test(){

        return getData1();
    }

    // 更新缓存
    @CachePut(value = {"testData"}, key = "'myData'")
    @GetMapping("/test1")
    public List<UserVo> test1(){
        List<UserVo> list = getData1();
        UserVo map1 = new UserVo();
        map1.setName("wuyu4");
        map1.setAge(24);
        list.add(map1);
        return list;
    }

    // 删除缓存
    @CacheEvict(value = {"testData"}, key = "'myData'", allEntries = true)
    @GetMapping("/test2")
    public String test2(){
        return "删除成功";
    }

    // 缓存组合操作，可以同时多个新增cacheable，多个修改put，多个删除evict
    @Caching(cacheable = {
            @Cacheable(value = {"testData"}, key = "'myData'"),
            @Cacheable(value = {"testData"}, key = "'myData1'"),
    })
    @GetMapping("/test3")
    public List<UserVo> test3(){
        return getData1();
    }

    public List<Map<String, Object>> getData(){
        System.out.println("获取数据，进来了。。。");
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "wuyu");
        map1.put("age", 21);
        list.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "wuyu");
        map2.put("age", 22);
        list.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("name", "wuyu");
        map3.put("age", 23);
        list.add(map3);
        return list;
    }

    public List<UserVo> getData1(){
        System.out.println("获取数据，进来了。。。");
        List<UserVo> list = new ArrayList<>();
        UserVo map1 = new UserVo();
        map1.setName("wuyu1");
        map1.setAge(21);
        list.add(map1);
        UserVo map2 = new UserVo();
        map2.setName("wuyu2");
        map2.setAge(22);
        list.add(map2);
        UserVo map3 = new UserVo();
        map3.setName("wuyu3");
        map3.setAge(23);
        list.add(map3);
        return list;
    }
}
